// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import {
    NotificationCenter
} from "../utils/NotificationCenter";

import {
    E2LProtocol,
    L2EProtocol,
    S2CProtocol,
    TIP_INFO,
    L2E_LOGIN,
} from "../proto/ELProtocol";

import {
    saveStorage,
    readStorage,
    adCoolDur,
    dailyAdCode
} from "../utils/CommonUtils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class LogicCenter extends cc.Component {

    private user: userInfo = null;

    // LIFE-CYCLE CALLBACKS:
   
    onLoad () {
        cc.game.addPersistRootNode(this.node);

        this.user = <userInfo>{};

        
        NotificationCenter.Instance.on(E2LProtocol.e2l_read_configs, this.readConfigs, this);
        NotificationCenter.Instance.on(E2LProtocol.e2l_update_qq_user, this.updateWxUserInfo, this);
        NotificationCenter.Instance.on(E2LProtocol.e2l_pop_pmd, this.popPmd, this);
        
        NotificationCenter.Instance.on(S2CProtocol.s2c_login, this.updateLoginData, this);
        NotificationCenter.Instance.on(S2CProtocol.s2c_req_adcode, this.updateAdCode, this);
        NotificationCenter.Instance.on(S2CProtocol.s2c_finish_ad, this.finishAd, this);

        NotificationCenter.Instance.on(S2CProtocol.s2c_exchange_trmb, this.exchangeTRMB, this);
        NotificationCenter.Instance.on(S2CProtocol.s2c_tixian, this.tixian, this);
        NotificationCenter.Instance.on(S2CProtocol.s2c_pmd_list, this.pmdList, this);
        NotificationCenter.Instance.on(S2CProtocol.s2c_bind_wx, this.bindWxInfo, this);

        
        if (cc.sys.WECHAT_GAME == cc.sys.platform) {
            // // this.videoAd = wx.createRewardedVideoAd({adUnitId: rewardVideo1});

            // // this.videoAd.onError(function(res){
            // //     console.log('videoAd onError',res);
            // // });

            // // this.videoAd.onLoad(function(res){
            // //     console.log('videoAd onLoad');
            // // });

            // // this.videoAd.onClose(function(res){
            // //     console.log('videoAd onClose',res);
            // //     if(res.isEnded == true) {
            // //         NotificationCenter.Instance.emit("requestFinishAd");
            // //     }
            // // });

            // const { screenWidth, screenHeight } = window['wx'].getSystemInfoSync();

            // if (this.bannerAd != null && this.bannerAd != undefined) {
            //     this.bannerAd.destroy();
            // }
            // this.bannerAd = window['wx'].createBannerAd({
            //     adUnitId: bannerAdIds[0],
            //     style: {
            //         top: screenHeight - 10,
            //         left: (screenWidth - 100) / 2,
            //         height:10,
            //         width: 100
            //     }
            // });
              
            // this.bannerAd.onResize(size => {
            //     // 底部居中显示
            //     this.bannerAd.style.top = screenHeight - size.height;
            //     this.bannerAd.style.left = (screenWidth - size.width) / 2;
            // });
            // this.bannerAd.onError(err => {
            //     console.log(err);
            // });
            // this.bannerAd.onLoad(() => {
            //     console.log("banner 广告加载成功");
            // });
            // this.bannerAd.hide();
        }
    }
    
    onDestroy() {
        NotificationCenter.Instance.off(E2LProtocol.e2l_read_configs, this.readConfigs, this);
        NotificationCenter.Instance.off(E2LProtocol.e2l_update_qq_user, this.updateWxUserInfo, this);
        NotificationCenter.Instance.off(E2LProtocol.e2l_pop_pmd, this.popPmd, this);
        
        NotificationCenter.Instance.off(S2CProtocol.s2c_login, this.updateLoginData, this);
        NotificationCenter.Instance.off(S2CProtocol.s2c_req_adcode, this.updateAdCode, this);
        NotificationCenter.Instance.off(S2CProtocol.s2c_finish_ad, this.finishAd, this);

        NotificationCenter.Instance.off(S2CProtocol.s2c_exchange_trmb, this.exchangeTRMB, this);
        
        NotificationCenter.Instance.off(S2CProtocol.s2c_tixian, this.tixian, this);
        NotificationCenter.Instance.off(S2CProtocol.s2c_pmd_list, this.pmdList, this);
        NotificationCenter.Instance.off(S2CProtocol.s2c_bind_wx, this.bindWxInfo, this);

        this.user = null;
    }
    
    
    // update (dt) {}


    public updateWxUserInfo(data: any) {
        this.user.nickName = data.nickName;
        this.user.headIcon = data.avatarUrl;
        // let info = <C2S_UPDATE_WX_INFO>{};
        // info.token = this.user.token;
        // info.nickName = this.user.nickName;
        // info.headIcon = this.user.headIcon;
    }

    public bindWxInfo(data: any) {
        if(data.nickName != null && data.nickName.length != 0) {
            this.user.nickName = data.nickName;
            NotificationCenter.Instance.emit(L2EProtocol.l2e_update_nickname, data.nickName);
        }
        if (data.headIcon != null && data.headIcon.length > 11) {
            this.user.headIcon = data.headIcon;
            NotificationCenter.Instance.emit(L2EProtocol.l2e_update_headIcon, data.headIcon);
        }
    }

    public updateLoginData(data: any) {
        this.user.playerId = data.playerId;
        if (cc.sys.WECHAT_GAME != cc.sys.platform && cc.sys.WECHAT_GAME_SUB != cc.sys.platform) {
            this.user.nickName = data.nickName;
            this.user.headIcon = data.headIcon;
        }

        this.user.myPromoterCode = data.myPromoterCode;
        this.user.myPromoterCode = this.user.myPromoterCode.replace('#', '_');

        this.user.adCD = 0;
        if (data.tfAdNum != null && data.tfAdNum != undefined) {
            this.user.tfAdNum = data.tfAdNum;
        }

        this.user.rmb = data.rmb/100;
        this.user.trmb = data.trmb;
        // this.user.minTRmbExchange = 1;
        this.user.minTRmbExchange = data.minTRmbExchange;
        this.user.bl = data.bl;

        this.user.adNum = data.adNum;
        this.user.sharedNum = data.sharedNum;
        this.user.getRMBNum = data.getRMBNum;


        this.user.token = data.token;
        saveStorage("token", data.token);

        // this.user.siteGuns = data.siteGuns.clone();
        // this.user.otherGuns = data.otherGuns.clone();
        let lastLoginTime = readStorage('lastLoginTime') || 0;
        this.user.loginServerTime = data.loginServerTime;

        let lastDate = new Date(Number(lastLoginTime));
        let currDate = new Date(data.loginServerTime);
        this.user.firstLogin = (lastDate.toDateString() != currDate.toDateString());
        saveStorage('lastLoginTime', data.loginServerTime);

        let updateData = <L2E_LOGIN>{};
        updateData.nickName = this.user.nickName;
        updateData.headIcon = this.user.headIcon;
        
        updateData.adGuideCode = data.adGuideCode;
        updateData.bl = data.bl;
        updateData.trmb = data.trmb;

        NotificationCenter.Instance.emit(L2EProtocol.l2e_login, updateData);

        // if (cc.sys.WECHAT_GAME == cc.sys.platform) {
            // console.log('qrcodeqrcodeqrcodeqrcodeqrcodeqrcode');
            // let strQR = readStorage('qrcode');
            // console.log("strQR:"+strQR);
            // if (strQR == null || strQR == '') {
                console.log('requestQRCoderequestQRCoderequestQRCoderequestQRCoderequestQRCoderequestQRCode');
                NotificationCenter.Instance.emit("requestQRCode");

                // NotificationCenter.Instance.emit("requestUpdateWxInfo");

            // }
        // }
    }

    public getUserInfo() : Object {
        return this.user;
    }
    

    public readConfigs() {
        let self = this;
        // this.configCounts = 4;
        // cc.loader.loadRes('configs/guns', function (err, jsonAsset) {
        //     self.gunUpdate = jsonAsset.json.guns;
        //     self.configCounts--;
        //     if (self.configCounts == 0) {
        //         cc.log("..................................");
                if (cc.sys.WECHAT_GAME == cc.sys.platform || cc.sys.WECHAT_GAME_SUB == cc.sys.platform) {
                    NotificationCenter.Instance.emit(L2EProtocol.l2e_check_qq_login);
                } else {
                    NotificationCenter.Instance.emit("requestLogin");
                }
        //     }
        // });
        
    }

    private updateAdCode(data: any) {
        // this.user.adNum = data.adNum;
        // this.user.sharedNum = data.sharedNum;
    }
    
    private finishAd(data: any) {
        if (data.adNum != null && data.adNum != undefined) {
            this.user.adNum = data.adNum;
        }
        if (data.tfAdNum != null && data.tfAdNum != undefined) {
            this.user.tfAdNum = data.tfAdNum;
        }
        this.user.adCD = adCoolDur;
        switch (data.finishdAdCode) {
            case dailyAdCode:
                {
                    this.user.trmb = data.trmb;
                    if (data.addtrmb > 0) {
                        NotificationCenter.Instance.emit('openReward', 'image/tubiao_xianjinquan', '现金券X'+String(data.trmb), 1.2);
                    }

                    NotificationCenter.Instance.emit(L2EProtocol.l2e_7day_pri);
            
                    // this.user.rpActivity = 0;
                    // NotificationCenter.Instance.emit(L2EProtocol.l2e_update_act_red, this.user.rpActivity);
                }
                break;
            // case freeCoinAdGuideCode:
            // case freeCoinAdGuideCode2:
            //     {
            //         this.user.coin = data.coin;
            //         let coinData = <L2E_COMMON_NUM>{};
            //         coinData.val = this.user.coin;
            //         NotificationCenter.Instance.emit(L2EProtocol.l2e_update_coin, coinData);
            //         if (data.addcoin > 0) {
            //             // let popData = <TIP_INFO>{};
            //             // popData.dur = 2.5;
            //             // popData.type = 1;
            //             // popData.resPath = "image/jinbi";
            //             // popData.count = data.addcoin;
            //             // NotificationCenter.Instance.emit('pop_tips', popData);
            //             NotificationCenter.Instance.emit('openReward', 'image/jinbi_da(2440)', '金币X'+simpleNum(data.addcoin), 1.2);
            //         }

            //         this.user.freeCoinBuff = data.freeCoinBuff;
            //         this.user.freeCoinCD = data.freeCoinCD;
            //         this.user.freeCoinLive = data.freeCoinLive;
            //         let updateData = <L2E_FREE_COIN>{};
            //         updateData.freeCoinCD = data.freeCoinCD;
            //         updateData.freeCoinLive = data.freeCoinLive;
            //         NotificationCenter.Instance.emit(L2EProtocol.l2e_free_coin, updateData);
            //     }
            //     break;

        }
    }

    private exchangeTRMB(data: any) {
        if (this.user.minTRmbExchange == 0) {
            this.user.minTRmbExchange = 1;
            NotificationCenter.Instance.emit(L2EProtocol.l2e_update_minTRMB, this.user.minTRmbExchange);
        }
        this.user.trmb = data.trmb;
        this.user.rmb = data.rmb/100;
        
        if (data.addrmb > 0) {
            // let popData = <TIP_INFO>{};
            // popData.dur = 1.5;
            // popData.type = 2;
            // popData.tip = '元宝兑换成功！';
            // NotificationCenter.Instance.emit('pop_tips', popData);
            NotificationCenter.Instance.emit('openReward', 'image/zhandui_jiangpin3', data.addrmb/100+'元', 1.2);
        }
        NotificationCenter.Instance.emit(L2EProtocol.l2e_update_rmb, this.user.rmb);
        NotificationCenter.Instance.emit(L2EProtocol.l2e_update_trmb, this.user.trmb);
    }

    private tixian(data: any) {
        this.user.rmb = data.rmb/100;
        let popData = <TIP_INFO>{};
        popData.dur = 1.5;
        popData.type = 2;
        popData.tip = '成功提现'+(-data.addrmb/100)+'元！';
        NotificationCenter.Instance.emit('pop_tips', popData);
        NotificationCenter.Instance.emit(L2EProtocol.l2e_tixian, this.user.rmb);
    }

    private pmdList(data: any) {
        this.user.pmdList = [];
        for (const key of Object.keys(data)) {
            if (data.hasOwnProperty(key)) {
                cc.log(data[key]);
                for (let i = 0; i < data[key].length; i++) {
                    const element = data[key][i];
                    this.user.pmdList.push(element);
                }
            }
        }

        if (this.user.pmdList.length > 0) {
            this.user.pmdList = this.user.pmdList.reverse();
            NotificationCenter.Instance.emit(L2EProtocol.l2e_pop_pmd, this.user.pmdList.pop());
        }
    }

    private popPmd() {
        if (this.user.pmdList.length > 0) {
            this.user.pmdList = this.user.pmdList.reverse();
            NotificationCenter.Instance.emit(L2EProtocol.l2e_pop_pmd, this.user.pmdList.pop());
        }else{
            NotificationCenter.Instance.emit(L2EProtocol.l2e_close_pmd);
        }
    }
}
